package w83b.xml;

import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.XMLReader;

import w83b.w83bUtilidadesComunes.W83bErrorCodes;
import w83b.xml.exception.W83bXmlException;



/**
 * @author cd00115i 
 */
public class W83bXmlUtilities implements java.io.Serializable{//NOPMD

	private static final long serialVersionUID = 1L;
	
	public static String getDescriptionLanguage(String xml,String locale) throws W83bXmlException{
		String description = "Undefined";
		W83bXmlDocument xmlDoc = new W83bXmlDocument();
		try {
			xmlDoc.createFromStringText(xml);
			W83bXmlElements elements = xmlDoc.getXmlElements("/description/language");
			for (int i=1;i<=elements.getCount();i++){
				W83bXmlElement element = elements.getItem(i);
				if (element.getAttribute("locale").equals(locale)){
					description = element.getValue();
					break;
				}
			}
			return description;
		} catch (W83bXmlException e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	final public static XMLReader makeXMLReader() { 
		try {
			final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            saxParserFactory.setValidating(false);
            saxParserFactory.setNamespaceAware(true);
            final SAXParser saxParser = saxParserFactory.newSAXParser();
            final XMLReader parser = saxParser.getXMLReader();
            return parser;//NOPMD
        } catch (Exception e) {
        }
        return null;
    }
	
	/**
	 * Escribe un nodo o documento XML
	 * @param node el nodo o documento XML que hay que escribir
	 * @param writer el objeto donde se escribe
	 * @throws W83bXmlException si hay algun problema durante la 
	 * transformacion del documento XML a texto plano.
	 */
	public static void xmlWriter(Node node, Writer writer) 
		throws W83bXmlException {
		
		// Use a Transformer for output
		TransformerFactory tFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = tFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
			DOMSource source = new DOMSource(node);
			StreamResult result = new StreamResult(writer);
			if (source!=null && result!=null)
			{
				transformer.transform(source, result);
			}
		} 
		catch (TransformerConfigurationException e) {
			log.log(Level.SEVERE,"W83b",e);
			throw new W83bXmlException(W83bErrorCodes.EC_EVALUATION_XML_ERROR);
		}
		catch (TransformerException e1) {
			log.log(Level.SEVERE,"W83b",e1);
			throw new W83bXmlException(W83bErrorCodes.EC_EVALUATION_XML_ERROR);
		} 		
	}
	
	/**
	 * Devuelve un nodo o documento XML como un String de texto plano.
	 * 
	 * @param node el nodo o documento XML
	 * @return el mismo documento, como un String
	 * @throws R02WXmlException si hay algun problema durante la 
	 * transformacion del documento XML a texto plano.
	 */
	public static String xmlToString(Node node) throws W83bXmlException {
		StringWriter stringWriter = new StringWriter();
		if (node != null)
		{
			xmlWriter(node, stringWriter);
		}
		return stringWriter.toString();
	}
	
	/**
	 * Devuelve un nuevo docuemto XML DOM
	 * @return el objeto Documento
	 * @throws W83bXmlException
	 */
	public static Document getNewDocument() throws W83bXmlException {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = null;
			builder = factory.newDocumentBuilder();
			return builder.newDocument();		
		}
		catch (Exception pcex) {
			log.log(Level.SEVERE,"W83b",pcex);
			// TODO poner bien el codigo de error aqui
			throw new W83bXmlException(W83bErrorCodes.EC_EVALUATION_XML_ERROR);
		}
	}

	public static Logger log = Logger.getLogger(W83bXmlUtilities.class.getName());//NOPMD

}
